package com.apes.enquiry.settle.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.settle.model.SupplierPlatformSettle;
import com.apes.enquiry.settle.repository.SupplierPlatformSettleRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("supplierPlatformSettleService")
public class SupplierPlatformSettleService extends DomainService {
    @Autowired
    private SupplierPlatformSettleRepository supplierPlatformSettleRepository;
    @Autowired
    private PartyRoleRepository partyRoleRepository;

    public Map createUser(SimpleRequest request){
        JSONObject user = new JSONObject();
        JSONObject jo = request.getJO();
        SimpleSession session = request.getSession();
        user.put("id",session.getUserId());
        user.put("name",session.getUserName());
        jo.put("user",user);
        return MapUtil.mapped(jo);
    }

    public void createSupplierPlatform(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        PartyRole supplier = partyRoleRepository.findOne(request.getJO().getJSONObject("supplier").getString("id"));
        if(supplier == null) return;
        SupplierPlatformSettle supplierPlatformSettle = request.getO(SupplierPlatformSettle.class);
        //判断标记
        boolean sign = false;
        //如果非创建状态单据在表里查询不到则不保存
        if(!"sent".equals(jsonObject.getString("stateType"))){
            if("approve".equals(jsonObject.getString("stateType"))){
                SupplierPlatformSettle platformSettle = supplierPlatformSettleRepository.findOne(supplierPlatformSettle.getId());
                if(platformSettle == null){
                    SupplierPlatformSettle saveAndFlush = supplierPlatformSettleRepository.saveAndFlush(supplierPlatformSettle);
                    saveAndFlush.setVersion(supplierPlatformSettle.getVersion() + 1);
                    sign = true;
                }
            }else {
                SupplierPlatformSettle platformSettle = supplierPlatformSettleRepository.findOne(supplierPlatformSettle.getId());
                if(platformSettle == null) sign = true;
            }
        }
        if(sign) return;
        supplierPlatformSettleRepository.saveAndFlush(supplierPlatformSettle);
    }
}
